import React, { useEffect, useState } from 'react';
import { Typography, Tag, Space, Button, message } from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { SearchTable } from '../../components/common/Table/SearchTable';
import { MaterialModal } from '../../components/common/Modal/MaterialModal';
import { ConfirmModal } from '../../components/common/Modal/ConfirmModal';
import { useMaterial } from '../../hooks/useMaterial';
import type { Material, CreateMaterialRequest, UpdateMaterialRequest } from '../../api/types/material';

const { Title } = Typography;

export const MaterialList: React.FC = () => {
  const {
    materials,
    loading,
    error,
    addMaterial,
    modifyMaterial,
    removeMaterial,
    getMaterials,
    resetError
  } = useMaterial();

  const [searchValue, setSearchValue] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingMaterial, setEditingMaterial] = useState<Material | null>(null);
  const [modalLoading, setModalLoading] = useState(false);

  // ConfirmModal 相关状态
  const [confirmModalVisible, setConfirmModalVisible] = useState(false);
  const [deletingMaterial, setDeletingMaterial] = useState<{ id: number, name: string } | null>(null);
  const [deleteLoading, setDeleteLoading] = useState(false);

  // 初始化数据
  useEffect(() => {
    getMaterials();
  }, [getMaterials]);

  // 错误处理
  useEffect(() => {
    if (error) {
      message.error(error);
      resetError();
    }
  }, [error, resetError]);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 60,
    },
    {
      title: '物资名称',
      dataIndex: 'name',
      key: 'name',
      width: 120,
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 100,
    },
    {
      title: '存放位置',
      dataIndex: 'location',
      key: 'location',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: string, record: Material) => {
        const statusConfig = {
          available: { color: 'green', text: '可用' },
          maintenance: { color: 'orange', text: '维护中' },
          scrapped: { color: 'red', text: '已报废' },
          borrowed: { color: 'blue', text: '借用中' }
        };
        const config = statusConfig[status as keyof typeof statusConfig];

        return (
          <Space direction="vertical" size={0}>
            <Tag color={config.color}>{config.text}</Tag>
            {status === 'borrowed' && record.borrowerName && (
              <span style={{ fontSize: '12px', color: '#666' }}>
                借用者: {record.borrowerName}
              </span>
            )}
          </Space>
        );
      }
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 150,
      ellipsis: true,
      render: (description: string) => description || '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: Material) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id, record.name)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 搜索处理
  const handleSearch = (value: string) => {
    setSearchValue(value);
  };

  // 打开新增弹窗
  const handleAdd = () => {
    setEditingMaterial(null);
    setIsModalVisible(true);
  };

  // 打开编辑弹窗
  const handleEdit = (material: Material) => {
    setEditingMaterial(material);
    setIsModalVisible(true);
  };

  // 提交表单（新增/编辑）
  const handleFormSubmit = async (values: UpdateMaterialRequest | CreateMaterialRequest) => {
    setModalLoading(true);
    try {
      if (editingMaterial) {
        // 编辑物资
        await modifyMaterial(editingMaterial.id, values as UpdateMaterialRequest);
        message.success('物资更新成功');
      } else {
        // 新增物资
        await addMaterial(values as CreateMaterialRequest);
        message.success('物资添加成功');
      }
      setIsModalVisible(false);
      setEditingMaterial(null);
    } catch (error) {
      console.error('操作失败:', error);
      // 错误信息由 hook 统一处理
      throw error;
    } finally {
      setModalLoading(false);
    }
  };

  // 删除物资 - 打开 ConfirmModal
  const handleDelete = (materialId: number, materialName: string) => {
    setDeletingMaterial({ id: materialId, name: materialName });
    setConfirmModalVisible(true);
  };

  // 确认删除
  const handleDeleteConfirm = async () => {
    if (!deletingMaterial) return;

    setDeleteLoading(true);
    try {
      await removeMaterial(deletingMaterial.id);
      message.success('物资删除成功');
      setConfirmModalVisible(false);
      setDeletingMaterial(null);
    } catch (error) {
      console.error('删除失败:', error);
      // 错误信息由 hook 统一处理
    } finally {
      setDeleteLoading(false);
    }
  };

  // 取消删除
  const handleDeleteCancel = () => {
    setConfirmModalVisible(false);
    setDeletingMaterial(null);
  };

  // 刷新列表
  const handleRefresh = () => {
    getMaterials();
    message.info('刷新物资列表');
  };

  // 取消表单
  const handleCancel = () => {
    setIsModalVisible(false);
    setEditingMaterial(null);
  };

  // 根据搜索值过滤数据
  const filteredData = materials.filter(material =>
    material.name.toLowerCase().includes(searchValue.toLowerCase()) ||
    material.category.toLowerCase().includes(searchValue.toLowerCase()) ||
    material.location.toLowerCase().includes(searchValue.toLowerCase()) ||
    (material.description && material.description.toLowerCase().includes(searchValue.toLowerCase()))
  );

  return (
    <div>
      <Title level={2}>物资管理</Title>

      <SearchTable<Material>
        tableTitle="物资列表"
        columns={columns}
        dataSource={filteredData}
        rowKey="id"
        onSearch={handleSearch}
        onAdd={handleAdd}
        onRefresh={handleRefresh}
        searchPlaceholder="搜索物资名称、分类、存放位置、描述..."
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
        }}
        loading={loading}
      />

      {/* 物资编辑/新增弹窗 */}
      <MaterialModal
        visible={isModalVisible}
        editingMaterial={editingMaterial}
        onSubmit={handleFormSubmit}
        onCancel={handleCancel}
        loading={modalLoading}
      />

      {/* 删除确认框 */}
      <ConfirmModal
        open={confirmModalVisible}
        title="确认删除"
        content={
          <div>
            <p>确定要删除物资 <strong>"{deletingMaterial?.name}"</strong> 吗？</p>
            <p style={{ color: '#ff4d4f' }}>此操作不可恢复，请谨慎操作！</p>
          </div>
        }
        onConfirm={handleDeleteConfirm}
        onCancel={handleDeleteCancel}
        type="danger"
        confirmText="删除"
        cancelText="取消"
        loading={deleteLoading}
      />
    </div>
  );
};

export default MaterialList;